package com.boot.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.constants.RedisKeys;
import com.boot.constants.StatusConstants;
import com.boot.entity.Question;
import com.boot.entity.User;
import com.boot.service.IQuestionService;
import com.boot.service.IUserService;
import com.boot.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class InProgressNotificationTask {

    @Resource
    private IQuestionService questionService;

    @Resource
    private IUserService userService;

    @Resource
    private MailService mailService;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    /**
     * 每隔 2 分钟执行一次
     */
    @Scheduled(fixedDelay = 2_000)
    public void scanAndNotifyPendingReviews() {
        log.info("[定时任务] 开始扫描已被接单的问题...");

        try {
            handleInProgressQuestions();
        } catch (Exception e) {
            log.error("【通知任务异常】" + e.getMessage(), e);
        }
    }

    /**
     * 扫描所有状态为 in_progress 但未通知的问题，向提问者发送提醒
     */
    private void handleInProgressQuestions() {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StatusConstants.QuestionStatus.IN_PROGRESS)
               .isNotNull("user_id"); // 确保有提问人

        List<Question> inProgressQuestions = questionService.list(wrapper);
        log.info("找到 {} 个处理中的问题待通知", inProgressQuestions.size());

        for (Question q : inProgressQuestions) {
            String idKey = String.valueOf(q.getId());

            // 检查是否已通知过
            Boolean hasNotified = redisTemplate.opsForSet().isMember(RedisKeys.SENT_IN_PROGRESS_NOTIFY, idKey);
            if (Boolean.TRUE.equals(hasNotified)) {
                continue;
            }

            try {
                User submitter = userService.getById(q.getUserId());
                if (submitter == null || submitter.getEmail() == null || submitter.getEmail().trim().isEmpty()) {
                    log.warn("问题ID={} 的提问人无邮箱，跳过通知", q.getId());
                    redisTemplate.opsForSet().add(RedisKeys.SENT_IN_PROGRESS_NOTIFY, idKey);
                    continue;
                }

                String subject = "🔧 您的问题正在处理中：" + truncate(q.getTitle(), 50);
                String content = buildQuestionInProgressToSubmitterEmail(submitter.getUsername(), q.getTitle());

                mailService.sendHtmlMail(submitter.getEmail(), subject, content);
                log.info("✅ 已发送“问题接单”通知给用户 {} (邮箱: {}), 问题ID={}", submitter.getUsername(), submitter.getEmail(), q.getId());

                // 标记为已通知
                redisTemplate.opsForSet().add(RedisKeys.SENT_IN_PROGRESS_NOTIFY, idKey);

            } catch (Exception e) {
                log.error("📧 发送“问题接单”通知失败（问题ID=" + q.getId() + "）：" + e.getMessage(), e);
            }
        }
    }

    // ==================== 邮件内容构建 ====================

    /**
     * 构建：问题被接单后，通知问题发布人
     */
    public String buildQuestionInProgressToSubmitterEmail(String submitterName, String questionTitle) {
        return "<div style='font-family: Arial, sans-serif; padding: 20px; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto;'>"
                    + "<h2 style='color: #2196F3;'>🔧 问题已进入处理阶段</h2>"
                    + "<p><strong>您好，" + escapeHtml(submitterName) + "：</strong></p>"
                    + "<p>您提出的问题 <em>“" + escapeHtml(questionTitle) + "”</em> 已被专家接单，当前状态为 <strong>“处理中”</strong>。</p>"
                    + "<p>我们已安排专业人员为您解答，请耐心等待。如有更新，系统将及时通知您。</p>"
                    + "<footer style='margin-top: 30px; color: #777; font-size: 0.9em; text-align: center;'>"
                    + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台</footer>"
                + "</div>";
    }

    // ==================== 工具方法 ====================

    private String escapeHtml(String str) {
        if (str == null) return "";
        return str.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#x27;");
    }

    private String truncate(String str, int len) {
        if (str == null) return "";
        return str.length() <= len ? str : str.substring(0, len) + "...";
    }
}
